﻿using ErrorOr;
using Gnivc.CarDealership.Api.Application.Abstractions.Repositories;
using Gnivc.CarDealership.Api.Domain.Entities;
using Gnivc.CarDealership.Api.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;

namespace Gnivc.CarDealership.Api.Infrastructure.Repositories;

public class BrandRepository : IBrandRepository
{
    private readonly IApplicationDbContext _context;

    public BrandRepository(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<ErrorOr<IEnumerable<Brand>>> GetAllAsync()
    {
        return await _context.Brands
            .AsNoTracking()
            .Where(b => !b.IsDeleted)
            .ToListAsync();
    }

    public async Task<ErrorOr<Brand?>> GetByIdAsync(Guid brandId)
    {
        var brand = await _context.Brands
            .Where(b => b.Id == brandId && !b.IsDeleted)
            .SingleOrDefaultAsync();

        if (brand == null)
            return Error.NotFound();

        return brand;
    }
    public async Task<ErrorOr<Created>> AddAsync(Brand brand)
    {
        await _context.Brands.AddAsync(brand);
        var result = await _context.SaveChangesAsync();

        if (result < 1)
            return Error.Unexpected();

        return new Created();
    }

    public async Task<ErrorOr<Updated>> UpdateAsync(Brand brand)
    {
        _context.Brands.Update(brand);
        var result = await _context.SaveChangesAsync();

        if(result < 1) 
            return Error.Unexpected();
        
        return new Updated();
    }

    public async Task<ErrorOr<Deleted>> DeleteAsync(Guid brandId)
    {
        var getBrandResult = await GetByIdAsync(brandId);

        if (getBrandResult.IsError)
            return getBrandResult.Errors;

        var brand = getBrandResult.Value!;

        brand.IsDeleted = true;

        var updateResult = await UpdateAsync(brand);

        if(updateResult.IsError)
            return updateResult.Errors;

        return new Deleted();
    }
}
